package com.isoft.service.impl;

import com.isoft.entity.BaseApueEntity;
import com.isoft.mapper.BaseApueMapper;
import com.isoft.service.BaseApueService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class BaseApueServiceImpl implements BaseApueService {
    private static final Logger logger = LoggerFactory.getLogger(BaseApueServiceImpl.class);

    @Autowired
    private BaseApueMapper baseApueMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(MultipartFile file) throws IOException {
        String xmlContent = new String(file.getBytes(), StandardCharsets.UTF_8);
        logger.info("Processing XML file: {}, size: {} bytes",
                file.getOriginalFilename(), file.getSize());
        return parseAndSave(xmlContent);
    }

    @Override
    public void parseAndSave(BaseApueEntity entity) {
        processAirportData(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML内容不能为空");
            }

            BaseApueEntity entity = xmlParserUtil.parseXml(xmlContent, BaseApueEntity.class);

            if (entity == null || entity.getApot() == null) {
                throw new IllegalArgumentException("XML结构无效");
            }

            return processAirportData(entity);
        } catch (Exception e) {
            logger.error("XML处理失败", e);
            throw new RuntimeException("处理XML失败: " + e.getMessage());
        }
    }

    private String processAirportData(BaseApueEntity entity) {
        String airportCode = entity.getApot().getAirportCode();
        String chineseName = entity.getApot().getChineseName();
        
        // 插入消息元数据（自动获取生成的ID）
        baseApueMapper.insertMeta(entity);

        try {
            // 尝试插入机场数据
            int affectedRows = baseApueMapper.insertAirport(entity);
            logger.info("插入机场数据完成，影响行数: {}, 生成的消息ID: {}",
                    affectedRows, entity.getMeta().getMsgId());
            return "机场数据处理成功。机场代码: " + airportCode + 
                   ", 机场名称: " + chineseName + 
                   ", 消息ID: " + entity.getMeta().getMsgId();
        } catch (DataIntegrityViolationException e) {
            // 检查是否是唯一性约束违反
            if (e.getMessage().contains("唯一性约束条件") || e.getMessage().contains("duplicate key")) {
                logger.warn("检测到重复的机场数据，机场代码: {}, 机场名称: {}", airportCode, chineseName);
                return "机场数据已存在，跳过重复数据。机场代码: " + airportCode + 
                       ", 机场名称: " + chineseName + 
                       ", 消息ID: " + entity.getMeta().getMsgId();
            } else {
                // 其他数据完整性错误，重新抛出
                throw e;
            }
        }
    }
}